package com.dmooo.ymx;


import android.app.PendingIntent;
import android.content.Context;
import android.os.StrictMode;
import android.support.multidex.MultiDexApplication;
import android.util.DisplayMetrics;
import android.util.Log;

import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeInitCallback;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.github.anzewei.parallaxbacklayout.ParallaxHelper;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.EaseUI;
import com.kepler.jd.Listener.AsyncInitListener;
import com.kepler.jd.login.KeplerApiManager;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.uuch.adlibrary.utils.DisplayUtil;
import com.dmooo.ymx.bean.Response;
import com.dmooo.ymx.bean.UserBean;
import com.dmooo.ymx.bean.UserInfoBean;
import com.dmooo.ymx.bean.VersionInformationBean;
import com.dmooo.ymx.common.SPUtils;
import com.dmooo.ymx.config.Constants;
import com.dmooo.ymx.https.HttpUtils;
import com.dmooo.ymx.https.onOKJsonHttpResponseHandler;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.jiguang.analytics.android.api.CalculateEvent;
import cn.jiguang.analytics.android.api.JAnalyticsInterface;
import cn.jpush.android.api.JPushInterface;
import cz.msebera.android.httpclient.Header;

/**
 * Created by yohn on 2018/7/6.
 */

public class CaiNiaoApplication extends MultiDexApplication {
    private static Context context;
    private static UserBean userBean; //用户信息，全局化调用
    private PendingIntent restartIntent;
    public static IWXAPI api;
    private static UserInfoBean userInfoBean;
    private static String registerid="";
    private SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
    private static CaiNiaoApplication instance;
    public static String getRegisterid() {
        return registerid;
    }

    public static void setRegisterid(String registerid) {
        CaiNiaoApplication.registerid = registerid;
    }
    public static CaiNiaoApplication getInstances(){
        return instance;
    }
    @Override
    public void onCreate() {
        //啦啦啦
        super.onCreate();
        context = getApplicationContext();// 获取Context
        instance=this;
        //微信注册
//        setDatabase();
        registerWeChat(context);
        registerActivityLifecycleCallbacks(ParallaxHelper.getInstance());
//        //极光推送初始化
        JPushInterface.setDebugMode(false);
        JPushInterface.init(this);
        JAnalyticsInterface.setDebugMode(false);
        JAnalyticsInterface.init(context);
        // android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
        initDisplayOpinion();
        Fresco.initialize(CaiNiaoApplication.getAppContext());


        AlibcTradeSDK.asyncInit(this, new AlibcTradeInitCallback() {
            @Override
            public void onSuccess() {
//                Toast.makeText(context, "初始化成功", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onFailure(int code, String msg) {
//                Toast.makeText(context, code+"", Toast.LENGTH_SHORT).show();
            }
        });
        if("1".equals(SPUtils.getStringData(this,"firstmb","1"))){
            SPUtils.saveStringData(this,"firstmb","0");
            SPUtils.saveStringData(this,"mbone","【{标题}】");
            SPUtils.saveStringData(this,"mbtwo","【在售价】{商品原价}");
            SPUtils.saveStringData(this,"mbthree","【券后价】{券后价}");
            SPUtils.saveStringData(this,"mbfour","【下载源曦默最高省】{佣金}元");
            SPUtils.saveStringData(this,"mbfive","複~製这条信息{淘口令}打开手机Tao寶即可查看");
        }
        CrashHandler.getInstance().init(this);
        CrashReport.initCrashReport(getApplicationContext(), "ddf7ca50b2", true);
//        int time=SPUtils.getIntData(this,format.format(new Date()),0);
//        //限制用户每天查询补丁次数，因为超过20次后会收费
//        if(time<=19){
//            time++;
//            SophixManager.getInstance().queryAndLoadNewPatch();
//            SPUtils.saveIntData(this,format.format(new Date()),time);
//        }


        //每天用户使用app统计
        if(SPUtils.getIntData(this,format.format(new Date())+"use",0)!=1){
            CalculateEvent calculateEvent=new CalculateEvent("openApp",1);
            JAnalyticsInterface.onEvent(this,calculateEvent);
            SPUtils.saveIntData(this,format.format(new Date())+"use",1);
        }
        RequestParams requestParams = new RequestParams();
        requestParams.put("cat_id",6);
        HttpUtils.post(Constants.GET_BANNER, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//                showToast(throwable.getMessage());
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    SPUtils.saveStringData(getAppContext(),"ade",responseString);
            }
        });
        HttpUtils.post(Constants.MESSAGE_ARTICLE_VERSION_URL, requestParams, new onOKJsonHttpResponseHandler<VersionInformationBean>(new TypeToken<Response<VersionInformationBean>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(int statusCode, Response<VersionInformationBean> datas) {
                if (datas.isSuccess()) {
                    final VersionInformationBean data = datas.getData();
                    if (data != null) {
                        SPUtils.saveStringData(context,"is_tm_11",data.is_tb_11);
                    }
                } else {
                }
            }
        });
        EMOptions options = new EMOptions();
        options.setAcceptInvitationAlways(false);
        options.setAutoTransferMessageAttachments(true);
        options.setAutoDownloadThumbnail(true);
        EMClient.getInstance().init(this, options);
        EMClient.getInstance().setDebugMode(true);
        EaseUI.getInstance().init(this, options);
    }
    private void initDisplayOpinion() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        DisplayUtil.density = dm.density;
        DisplayUtil.densityDPI = dm.densityDpi;
        DisplayUtil.screenWidthPx = dm.widthPixels;
        DisplayUtil.screenhightPx = dm.heightPixels;
        DisplayUtil.screenWidthDip = DisplayUtil.px2dip(getApplicationContext(), dm.widthPixels);
        DisplayUtil.screenHightDip = DisplayUtil.px2dip(getApplicationContext(), dm.heightPixels);
    }

    public static Context getAppContext() {
        return context;
    }

    public static UserInfoBean getUserInfoBean() {
        return userInfoBean;
    }

    public static void setUserInfoBean(UserInfoBean userInfoBean1) {
        userInfoBean = userInfoBean1;
    }

    public static UserBean getUserBean() {
        return userBean;
    }

    public static void setUserBean(UserBean userBean1) {
        userBean = userBean1;
    }

    public static  void registerWeChat(Context context) {   //向微信注册app
        api = WXAPIFactory.createWXAPI(context, Constants.WX_APP_ID, true);
        api.registerApp(Constants.WX_APP_ID);
        KeplerApiManager.asyncInitSdk(instance, Constants.JD_CLIENT_ID,  Constants.JD_SECRET,
                new AsyncInitListener() {
                    @Override
                    public void onSuccess() {
// TODO Auto-generated method stub
                        Log.e("Kepler", "Kepler asyncInitSdk onSuccess ");
                    }
                    @Override
                    public void onFailure() {
// TODO Auto-generated method stub
                        Log.e("Kepler",
                                "Kepler asyncInitSdk 授权失败，请检查 lib 工程资源引用；包名,签名证书是否和注册一致");
                    }
                });
    }
}
